<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 输入框和按钮区域 -->
      <el-row :gutter="25">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            clearable
            v-model="queryInfo.query"
            @keyup.enter.native="getGoodsList"
            @clear="getGoodsList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getGoodsList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="goAddPage">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- table表格区域 -->
      <el-table :data="goodsList" style="width: 100%" stripe border>
        <el-table-column type="index" label="#" :resizable="false">
        </el-table-column>
        <el-table-column prop="goods_name" label="商品名称" :resizable="false">
        </el-table-column>
        <el-table-column
          prop="goods_price"
          label="商品价格(元)"
          width="105px"
          :resizable="false"
        >
        </el-table-column>
        <el-table-column
          prop="goods_weight"
          label="商品重量"
          width="80px"
          :resizable="false"
        >
        </el-table-column>
        <el-table-column label="创建时间" width="165px" :resizable="false">
          <template v-slot="shuju">
            {{ shuju.row.add_time | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140px" :resizable="false">
          <template v-slot="shuju">
            <!-- 修改按键 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="showDialogVisible(shuju.row.goods_id)"
            ></el-button>
            <!-- 删除按键 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="removeById(shuju.row.goods_id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>

    <!-- 编辑商品对话框 -->
    <el-dialog title="修改信息" :visible.sync="editDialogVisible" width="50%">
      <el-form
        :model="editGoodForm"
        :rules="editGoodFormRules"
        label-width="100px"
        ref="editGoodFormRef"
      >
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="editGoodForm.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
          <el-input
            type="number"
            v-model="editGoodForm.goods_weight"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input type="number" v-model="editGoodForm.goods_price"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUpdate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'List',
  data() {
    return {
      // 查询参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10,
      },
      // 商品列表数据
      goodsList: [],
      // 总数据条数
      total: 0,
      // 编辑商品对话框是否显示
      editDialogVisible: false,
      // 商品的信息对象
      editGoodForm: {},
      // 编辑商品信息校验规则
      editGoodFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称！', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格!', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量!', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    // 根据分页获取对应的商品列表
    async getGoodsList() {
      const { data: res } = await this.$http.get('goods', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message({
          duration: 2000,
          message: '获取商品列表数据失败！',
          type: 'error',
        })
      }
      this.goodsList = res.data.goods
      this.total = res.data.total
    },
    // 监听 pageSize 的改变事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getGoodsList()
    },
    // 监听页码值改变事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getGoodsList()
    },
    // 根据id删除商品
    async removeById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该商品, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //  如果用户确认删除，则返回值为 confirm
      //  如果用户取消删除，则返回值为 cancel
      if (confirmResult !== 'confirm') {
        return this.$message({
          duration: 2000,
          message: '取消删除商品！',
          type: 'info',
        })
      }
      const { data: res } = await this.$http.delete(`goods/${id}`)
      if (res.meta.status !== 200) {
        return this.$message({
          duration: 2000,
          message: '删除商品失败！',
          type: 'error',
        })
      }
      this.$message({
        duration: 2000,
        message: '删除商品成功！',
        type: 'success',
      })
      // 重新渲染商品列表
      this.getGoodsList()
    },
    // 展示编辑商品的对话框
    async showDialogVisible(id) {
      const { data: res } = await this.$http.get(`goods/${id}`)
      if (res.meta.status !== 200) {
        return this.$message({
          duration: 2000,
          message: '查询商品信息失败！',
          type: 'error',
        })
      }
      this.editGoodForm = res.data
      this.editDialogVisible = true
    },
    // 修改商品信息
    async saveUpdate() {
      const { data: res } = await this.$http.put(
        `goods/${this.editGoodForm.goods_id}`,
        this.editGoodForm
      )
      if (res.meta.status !== 200) {
        return this.$message({
          duration: 2000,
          message: '修改商品信息失败！',
          type: 'error',
        })
      }
      this.$message({
        duration: 2000,
        message: '修改商品信息成功！',
        type: 'success',
      })
      this.getGoodsList()
      this.editDialogVisible = false
    },
    // 跳转到添加商品页面
    goAddPage() {
      this.$router.push('/goods/add')
    },
  },
}
</script>

<style scoped>
.el-table {
  font-size: 14px;
}
</style>
